<template>
    <div class="body">
        <div id="content" class="typing_content font3">
            <el-button type="primary" plain style="position: fixed;left: 10px;top: 100px;" v-on:click="speak">语音播放</el-button>
            <el-button type="primary" plain style="position: fixed;left: 0;top: 132px;" v-on:click="pause">语音暂停</el-button>
            <el-button type="primary" plain style="position: fixed;left: 0;top: 164px;" v-on:click="resume">语音继续</el-button>
            <el-button type="primary" plain style="position: fixed;left: 0;top: 196px;" v-on:click="cancel">语音重置</el-button>
            <div
                    v-for="(item, index) of this.text_array"
                    :id="getID(index)"
                    class="typing"
                    :class="index == 0 ? 'typing_on' : ''"
                    :key="index"
            >
                <div class="text" style="overflow:hidden;">
                    <!--<span>{{item}}</span>-->
                    <span
                            v-for="(v, dex) in item"
                            :key="dex"
                            :class="{'yc':v.match(/[`~!@#$^&*()=|{}':;',\\.<>\?~！@#￥……&*（）——|{}【】‘；：”“'。，、？-]/)===null}"
                            style="white-space: pre"
                            >{{ v }}</span
                    >
                </div>
                <input
                        oncopy="return false"
                        onpaste="return false"
                        oncut="return false"
                        autocomplete="off"
                        name="n9ef7e0260c549a82[]"
                        @input="flag ? inputChange($event, index) : ''"
                        @compositionstart="flag = false"
                        @compositionend="test($event, index)"
                        :readonly="index !== 0 ? true : false"
                        type="text"
                        class="typing"
                        value=""
                        data-bug="true"
                        :data-index="index"
                />
            </div>
        </div>
        <div id="typing_info" style="display: block; margin-right: 0px">
            <div id="typing_info_li">
                <ul>
                    <li class="daojishi">
                        <div></div>
                        倒计时
                    </li>
                    <li class="daojishi_time">{{ this.residue }}</li>
                    <li class="sheding">设定时间：{{ this.time }}分钟</li>
                    <li class="sudu">速&nbsp;度：{{ speed }} KPM</li>
                    <li class="zhengquelv">正确率：{{ accuracy }} %</li>
                    <li class="cuowu">错&nbsp;误：{{ this.error }} 字</li>
                    <li class="tuige">退&nbsp;格：0 次</li>
                    <li class="zongzishu">总字数：{{ inputLength }} 字</li>
                </ul>
            </div>
        </div>
        <div class="window"></div>
        <div class="info_div" style="margin-left: -200px; margin-top: 261px">
            <div class="typing_end_div2">设定时间已到！</div>
            <h4>测试结果（英文打字）</h4>
            <div class="typing_end_div">
                时间：<strong>{{ time }}</strong
            >分钟，速度：<strong>{{ speed }}</strong
            >KPM，正确率：<strong>{{ accuracy }}</strong
            >%
            </div>
            <div class="button_div">
        <span id="box_button_span_ts"
        ><strong style="color: red; font-size: 24px"
        >请勿再操作!</strong
        ></span
        >
                <div class="clear"></div>
            </div>
        </div>
    </div>
</template>

<script>
    import $ from "jquery";
    import {mapState} from 'vuex';
    export default {
        // import $ from ''
        name: "bodyaa",
        data() {
            return {
                text: "",
                text_check_array: [],
                text_check: "",
                text_array: [],
                error: 0,
                right: 0,
                total: 0,
                time: 10,
                residue: "",
                first: true,
                times: 0,
                flag: true,
                xh: "",
                xm: "",
                bug: 0,
                bug2: 0,
                typing: [],
                name: "",
                contest:false,
                exercise:true,
                utterThis:''
            };
        },
        async created() {
            this.time=this.$route.query.time||10;

            let res = "";
            // res = await this.$cloudbase
            //     .auth({ persistence: "local" })
            //     .anonymousAuthProvider()
            //     .signIn();

            res = await this.$cloudbase
                .database()
                .collection('ykf_student')
                .where({Student_number:'07190749赵旭东'})
                .get();
            this.contest = Boolean(res.data[0].contest)
            //
            function over(text,that) {
                alert(text)
                that.$router.go(-1)
                // alert(this.$route)
                // console.log(this)
            }

            if (!this.contest&&this.$route.query.begin){
                over('不在比赛时间内',this)
            }
            if (this.contest&&this.$route.query.begin) {
                this.typing = await this.$cloudbase
                    .database()
                    .collection('typing_contest')
                    .where({name: this.Authorization})
                    .get()
                this.typing = this.typing.data[0]
                if (!this.typing.hear_contest) {
                    over('您的录入已结束',this)
                }
            }

            let article = 11
            if (!this.$route.query.begin){
                await this.$prompt('文章编号11-20，默认为11', '输入文章编号', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputPattern: /^[1-9][0-9]{0,}$/,
                    inputErrorMessage: '请输入编号11-20'
                }).then(({ value }) => {
                    this.$message({
                        type: 'success',
                        message: '你选择的文章编号是 ' + value,
                    })
                    if (value<11||value>21){
                        this.$message({
                            type: 'success',
                            message: '你选择的文章编号超出预设，默认11文章 '
                        })
                        value = 11
                    }
                    article = Number(value)
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '默认11文章'
                    });
                });
            }
            if (article>20){
                article=11
            }
            res = await this.$cloudbase.database().collection("article").where({serialNumber:article}).get();

            this.text = res.data[0].str;
            // console.log(this.text.replace(/[`~!@#$^&*()=|{}':;',\\.<>\\?~！@#￥……&*（）——|{}【】‘；：”“'。，、？-]/,''))
            this.text = this.text.replace(/[`~!@#$^&*()=|{}':;',\\.<>\\?~！@#￥……&*（）——|{}《》【】‘；：”“'。，、？-]/g,'')

            this.residue = this.time + ":00";
            this.text_check = this.text;
            while (this.text.length != 0) {
                this.text_array.push(this.text.substring(0, 43));
                this.text = this.text.slice(43);
            }
            this.utterThis = new window.SpeechSynthesisUtterance(res.data[0].str)
            window.speechSynthesis.cancel(this.utterThis)


        },
        methods: {
            speak(){
                window.speechSynthesis.speak(this.utterThis)
                this.$store.dispatch('updateUtterFun',this.utterThis)
            },
            pause(){
                window.speechSynthesis.pause(this.utterThis)
            },
            resume(){
                window.speechSynthesis.resume(this.utterThis)
            },
            cancel(){
                window.speechSynthesis.cancel(this.utterThis)
            },
            handleSelect(key, keyPath) {
                console.log(key, keyPath);
            },
            test: function (a, b) {
                this.flag = true;
                this.inputChange(a, b);
            },
            getID: function (index) {
                return "i_" + index;
            },
            // input输入
            inputChange: function (e, index) {
                if (this.first) {
                    this.CountDown();
                    this.first = false;
                }
                let ls = e.path[0].value;
                let ls2 = e.path[1];
                if (e.path[0].value.length >= 43) {
                    if (e.path[0].value.length > 43) {
                        $(
                            "#i_" + (index + 1)
                        )[0].children[1].value = e.path[0].value.substring(43);
                        e.path[0].value = e.path[0].value.substring(0, 43);
                    }
                    $("#i_" + index)[0].classList.remove("typing_on");
                    $("#i_" + (index + 1))[0].classList.add("typing_on");
                    e.path[0].readOnly = true;
                    $("#i_" + (index + 1))[0].children[1].readOnly = false;
                    $("#i_" + (index + 1))[0].children[1].focus();
                } else if (e.path[0].value.length == 0 && e.code == "Backspace") {
                    let val = $("#i_" + (index - 1))[0].children[1].value;

                    ls = val.substr(0, val.length - 1);
                    $("#i_" + (index - 1))[0].children[1].value = ls;
                    ls2 = $("#i_" + (index - 1))[0];
                    // console.log(1)
                    $("#i_" + index)[0].classList.remove("typing_on");
                    $("#i_" + (index - 1))[0].classList.add("typing_on");
                    e.path[0].readOnly = true;
                    $("#i_" + (index - 1))[0].children[1].readOnly = false;
                    $("#i_" + (index - 1))[0].children[1].focus();
                }
                for (let i = 0; i < ls.length; i++) {
                    if (ls[i] == ls2.children[0].children[i].innerText) {
                        ls2.children[0].children[i].style.background = "none";
                        ls2.children[0].children[i].style.color = "green";
                        ls2.children[0].children[i].style.opacity = "1";
                    } else {
                        ls2.children[0].children[i].style.background = "red";
                        ls2.children[0].children[i].style.color = "rgba(0,0,0,0)";

                        ls2.children[0].children[i].style.opacity = "0";
                    }
                }
                this.text_check_array[index] = e.target.value;
                this.error = 0;
                this.bug -= e.target.value.length;
                if (this.bug > 0) {
                    for (let i = 0; i < this.bug; i++) {
                        ls2.children[0].children[ls.length + i].style.background = "none";
                        ls2.children[0].children[ls.length + i].style.color = "rgba(0,0,0,0)";
                        ls2.children[0].children[ls.length + i].style.opacity='0'
                    }
                }
                this.text = this.text_check_array.join("");
                this.total = this.text.length;
                this.bug = e.target.value.length;
            },
            CountDown: function () {
                let maxtime = this.time * 60 - 1;
                let vm = this;
                this.times = 0;
                let that = this;
                // let res
                // let exercise = '';

                let timer = setInterval(async function () {
                    if (maxtime >= 0) {
                        vm.times++;
                        let minutes = Math.floor(maxtime / 60);
                        let seconds = Math.floor(maxtime % 60);
                        seconds < 10 ? (seconds = "0" + seconds) : "";
                        vm.$set(vm.$data, "residue", minutes + ":" + seconds);
                        maxtime--;
                    } else {
                        clearInterval(timer);
                        $("input").blur();
                        $(".window").css("display", "block");
                        $(".info_div").css("display", "block");
                    }

                    if (that.contest&&that.$route.query.begin){
                        await that.$cloudbase
                            .database()
                            .collection("typing_contest")
                            .where({name:that.Authorization})
                            .update({
                                name: that.Authorization,
                                hear_speed: that.speed,
                                hear_ratio: that.accuracy,
                                hear_str: that.text,
                                hear_contest:false
                            });
                    }else if (that.time==10){
                        await that.$cloudbase
                            .database()
                            .collection("typing")
                            .where({name:that.Authorization})
                            .update({
                                name: that.Authorization,
                                hear_speed: that.speed,
                                hear_ratio: that.accuracy,
                                hear_str: that.text
                            });
                    }
                }, 1000);
            },
        },
        computed: {
            ...mapState({
                Authorization: state=>state.Authorization
            }),
            inputLength: function () {
                return this.total;
            },
            accuracy: function () {
                return parseInt(((this.total - this.error) / this.total) * 100) || 0;
            },
            speed: function () {
                let zmmin = ((this.total - this.error) / this.times) * 60;
                zmmin = Math.round(zmmin);
                if (isNaN(zmmin)) {
                    zmmin = 0;
                }
                return zmmin == "Infinity" ? 0 : zmmin;
            },
        },
        watch: {
            total(val) {
                this.error = 0;
                for (let i = 0; i < val; i++) {
                    if (this.text[i] != this.text_check[i]) {
                        this.error++;
                    }
                }
            },
        },
        async mounted() {
            let that = this;

            $(document).keydown(function (event) {
                if (
                    event.originalEvent.code == "Backspace" &&
                    event.target.getAttribute("data-bug")
                ) {
                    if (
                        event.target.value == "" &&
                        event.target.getAttribute("data-index") != 0
                    ) {
                        that.inputChange(
                            event.originalEvent,
                            event.target.getAttribute("data-index")
                        );
                    }
                }
            });
        },
    };
</script>

<style scoped>
</style>